package com.zlx.xBiaoShop.controller;


import com.zlx.xBiaoShop.entity.RecvAddr;
import com.zlx.xBiaoShop.entity.Result;
import com.zlx.xBiaoShop.entity.User;
import com.zlx.xBiaoShop.service.RecvAddrService;
import com.zlx.xBiaoShop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/recvAddr")
public class RecvAddrController {
    @Autowired
    private RecvAddrService recvAddrService;
    @Autowired
    private UserService userService;

    /*
        根据用户id查询所有收货地址
     */
    @GetMapping("findAllAddrByUserId/{userId}")
    public Result findAllAddrByUserId(@PathVariable Integer userId){
        List<RecvAddr> allAddrByUserId = recvAddrService.findAllAddrByUserId(userId);
        return new Result(allAddrByUserId);
    }
    /*
        根据ID删除地址
     */
    @DeleteMapping("deleteAddrById/{id}")
    public Result deleteAddrById(@PathVariable Integer id){
        recvAddrService.deleteById(id);
        return new Result(true,"删除完成",null);
    }
    @PostMapping("addAddr/{flag}")
    public Result addAddr(@RequestBody RecvAddr addr, @PathVariable Boolean flag, HttpSession session){
        User loginUser = (User) session.getAttribute("loginUser");
        Integer addId = recvAddrService.save(addr, flag, loginUser.getId());
        if (flag){
            //是否是设置默认地址
            userService.changeDefalutAddr(loginUser.getId(),addId);
        }
        return new Result(true,"添加地址成功！",addId);
    }
    /*
        获取默认地址
     */
    @GetMapping("getDefaultAddr/{userId}/{defaultId}")
    public Result getDefaultAddr(@PathVariable Integer userId,@PathVariable Integer defaultId){
        return new Result(recvAddrService.getDefaultAddr(userId,defaultId));
    }
}
